import { IStrategyOptions, Strategy } from "passport-local";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthService } from "./auth.service";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super(
      {
        usernameField: "account",
        passwordField: "password"
      } as IStrategyOptions
    );
  }

  async validate(account: string, password: string): Promise<any> {
    //如果找到账户就会返回在请求头中否则返回错误
    const _account = await this.authService.validateUser(account, password);
    if (!_account) {
      throw new UnauthorizedException();
    }
    return _account;
  }
}